package start;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.HashMap;
import java.util.Map;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

public class JdbcSpitterDAO implements SpitterDAO {
    private SimpleJdbcTemplate jdbcTemplate;
    private final String SQL_INSERT_SPITTER = "insert into spitter(username,password,fullname) values(?,?,?)";
    private final String SQL_INSERT_SPITTER_NAMED = "insert into spitter(username,password,fullname) values(:username,:password,:fullname)";
    private final String SQL_SELECT_SPITTER_BY_ID = "select id,username,password,fullname from spitter where id=?";

    public JdbcSpitterDAO() {
        super();
    }

    public void setJdbcTemplate(SimpleJdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void addSpitter(Spitter spitter) {
        jdbcTemplate.update(SQL_INSERT_SPITTER, spitter.getUsername(), spitter.getPassword(), spitter.getFullName());
    }

    @Override
    public Spitter getSpitterById(long id) {
        return jdbcTemplate.queryForObject(SQL_SELECT_SPITTER_BY_ID, new ParameterizedRowMapper<Spitter>() {
                @Override
                public Spitter mapRow(ResultSet rs, int rowNum) throws SQLException {
                    Spitter spitter = new Spitter();
                    spitter.setId(rs.getLong(1));
                    spitter.setUsername(rs.getString(2));
                    spitter.setPassword(rs.getString(3));
                    spitter.setFullName(rs.getString(4));
                    return spitter;
                }
            }, id);
    }

    @Override
    public void addSpitterNamedParam(Spitter spitter) {
        Map<String,Object>params=new HashMap<String,Object>();
        params.put("username",spitter.getUsername());
        params.put("password",spitter.getPassword());
        params.put("fullname",spitter.getFullName());
        jdbcTemplate.update(SQL_INSERT_SPITTER_NAMED, params);
    }
}
